<template>
	<view style="margin: 10px;background-color: #fff;border-radius: 10px;">
		1111
	    <!-- <view style="padding: 15px;padding-top: 15px;">
			<uni-forms ref="baseForm" :rules="rules" :modelValue="FormData">
				
				<uni-forms-item label="检查人:">
					<uni-easyinput v-model="FormData.userName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="部门:" v-if="!singleShop">
					<uni-easyinput v-model="deptName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="车间:" required name="workshopId">
					<uni-data-select
						v-if="!singleShop"
						v-model="FormData.workshopId"
						:localdata="shopOption"
						@change="shopChange"
						:clear="false"
					></uni-data-select>
					<uni-easyinput v-if="singleShop" v-model="FormData.workshopId" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="检查区域:" required name="workshopareaId">
					<uni-data-select
					    v-model="FormData.workshopareaId"
					    :localdata="spaceOption"
						:clear="false"
					></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="6源问题:">
					<view style="line-height: 35px;">
						<uni-data-checkbox style="display: inline-block;" v-model="selectValue" :localdata="selectOption"  @change="selChange"></uni-data-checkbox>
						<uni-data-select 
						   v-if="sourceShow"
						   style="display: inline-block;width: 45%;"
						    v-model="FormData.sixProblem"
						    :localdata="sourceOption"
							:clear="false"
						></uni-data-select>
					</view>
				</uni-forms-item>
				<uni-forms-item label="检查时间:" required name="createTime">
					<uni-datetime-picker type="datetime" :clear-icon="false" v-model="FormData.createTime" @maskClick="maskClick" />
				</uni-forms-item>
				<uni-forms-item label="问题描述:" required name="description">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.description" placeholder="请输入问题"/>
				
				</uni-forms-item>
				<uni-forms-item label="图片上传:" required name="frontImage">
					<uni-file-picker class="form-up-file" fileMediatype="image" :image-styles="imageStyles" ref="filePicker" :file-list="imageList" limit="1" @progress="progress" @select='onFileChange' @delete='imgDelet'></uni-file-picker>
				</uni-forms-item>
			</uni-forms>
			<view>
					<button type="primary" class="uni-button-color" :disabled="isSubmitting"
      :loading="isSubmitting" @click="handleSubmit()">{{ isSubmitting ? '提交中...' : '提交' }}</button>
				</view>
		</view> -->
	</view>
</template>

<script>
	import { post, fileUpLoad, postForm } from '../../utils/request.js';
	export default {
		data() {
			return {
				// 校验规则
				rules: {
					frontImage: {
						rules: [{
							required: true,
							errorMessage: '请上传图片'
						}]
					},
					workshopareaId: {
						rules: [{
							required: true,
							errorMessage: '请选择检查区域'
						}]
					},
					workshopId: {
						rules: [{
							required: true,
							errorMessage: '请选择车间'
						}]
					},
					description: {
						rules: [{
							required: true,
							errorMessage: '请输入问题描述'
						}]
					},
					createTime: {
						rules: [{
							required: true,
							errorMessage: '请选择检测时间'
						}]
					}
				},
				isSubmitting: false,
				lastSubmitTime: 0,
				selectValue: 0,
				selectOption: [
					{
					 text: '否',
					 value: 0
					},
					{
					 text: '是',
					 value: 1
					},
				],
				sourceOption: [
					{ value: '故障源', text: "故障源" },
					{ value: '危险源', text: "危险源" },
					{ value: '缺陷源', text: "缺陷源" },
					{ value: '浪费源', text: "浪费源" },
					{ value: '污染源', text: "污染源" },
					{ value: '清扫困难源', text: "清扫困难源" },
				],
				sourceShow: false,
				popupName: 'name',
				deptName: '',
				singleShop: false,
				imageList: [],
				imageStyles:{
					width:70,
					height:70,
					border:{
						color:"rgb(238, 238, 238)",
						width:2,
						style:'dashed',
						radius:'2px'
					}
				},
				title: '',
				userInfor: uni.getStorageSync('userInfor'),
				workshopName: '',
				userName: '',
				FormData: {
					checkUserId: '',
					createTime: Date.now(),
					sixProblem: '',
					description: '',
					frontImage: '',
					workshopId: '',
					workshopareaId: '',
					deptName: ''
				},
				recommendations: [], // 推荐内容列表
				recommendationsDes: [], // 推荐内容列表
				shopOption: [],
				spaceOption: [],
				single:  Date.now(),
				selectTab: 0,
				selected: {
					'点检问题': 0
				}
			}
		},
		onShow() {
			let that = this
			this.userInfor = uni.getStorageSync('userInfor')
			this.userName = this.userInfor.userName
			this.FormData.userName = this.userInfor.name
			this.deptName = this.userInfor.deptName
			this.workshopName = this.userInfor.workshop
			this.workshopareaId = this.userInfor.workshopareaId
			//this.FormData.workshopId = this.userInfor.workshopId
			this.FormData.checkUserId = this.userInfor.userId
			uni.$on('switchTabData', (data) => {
			      console.log('接收到的参数:', data); // { id: 123, name: 'test' }
				  let id = data.id
				  if(id == 1) {
					  //debugger
					that.clearData()	
				  }
			});
		},
		onTabItemTap() {
			//debugger
			this.clearData()
			//this.imgDelet()
		},
		onLoad() {
			this.updataInfor()
			console.log(this.userName, 'this.userName')
			//this.getInfor()
		},
		methods: {
			clearData() {
				//debugger
				let shop = this.userInfor.workshopList
				this.FormData.createTime = Date.now()
				this.FormData.description = ''
				this.FormData.deptName = ''
				this.FormData.frontImage = ''
				this.FormData.workshopareaId = ''
				this.FormData.sixProblem = ''
				this.selectValue = 0
				this.sourceShow = false
				this.imageList = []
				if(shop.length > 1) {
					this.FormData.workshopId = ''
				}
				this.$refs.filePicker.clearFiles();
			},
			// 处理输入事件
			nameInput() {
			    if (this.FormData.name) {
			      // 模拟推荐内容
			      this.recommendations = this.getNames(this.FormData.name);
			      this.$refs.namePopup.open(); // 打开弹框
			    } else {
			      this.recommendations = [];
			      this.$refs.namePopup.close(); // 关闭弹框
			    }
			},
			// 处理输入事件
			descriptionInput() {
			    if (this.FormData.description) {
			      // 模拟推荐内容
			      this.recommendationsDes = this.getDescriptions(this.FormData.description);
			      this.$refs.descriptionsPopup.open(); // 打开弹框
				  //debugger
			    } else {
			      this.recommendationsDes = [];
			      this.$refs.descriptionsPopup.close(); // 关闭弹框
			    }
			},
			  // 模拟获取推荐内容
			getNames(query) {
			    const allRecommendations = ['问题测试1', '测试2', '测试3', '测试4', '问题1', '问题2'];
			    return allRecommendations.filter(item => item.includes(query));
			},
			  // 模拟获取推荐内容
			getDescriptions(query) {
			    const allRecommendationsDes = ['描述1', '描述2', '描述3', '测试4', '问题1', '问题2'];
				//debugger
			    return allRecommendationsDes.filter(item => item.includes(query));
			},
			selChange(e) {
				console.log(e)
				if(e.detail.value === 1) {
					this.sourceShow = true
				} else {
					this.sourceShow = false
					this.FormData.sixProblem = ''
				}
			},
			  // 选择推荐内容
			selectName(item) {
				this.FormData.name = item;
			    this.$refs.namePopup.close(); // 关闭弹框
			},
			  // 选择推荐内容
			selectDescription(item) {
				this.FormData.description = item;
			    this.$refs.descriptionsPopup.close(); // 关闭弹框
			},
			closepopName() {
				this.$refs.namePopup.close();
			},
			closepopDescrip() {
				this.$refs.descriptionsPopup.close(); 
			},
			async handleSubmit() {
			      // 防抖处理：1秒内只能提交一次
			      const now = Date.now();
				  console.log(now - this.lastSubmitTime, '111')
			      if (now - this.lastSubmitTime < 3000) {
			        return;
			      }
			      this.lastSubmitTime = now;
			      
			      // 防止重复提交
			      if (this.isSubmitting) return;
			      this.isSubmitting = true;
			      
			      try {
			        this.clickInter('baseForm');
			        // 处理成功逻辑
			      } catch (error) {
			        // 处理错误逻辑
			      } finally {
			        this.isSubmitting = false;
			      }
			    },
			clickInter(ref){
				if(this.singleShop) {
					this.FormData.workshopId = this.shopOption[0].value
				}
				console.log(this.FormData, 'this.FormData')
				 //debugger
				this.$refs[ref].validate().then(res => {
					this.FormData.checkUserId = this.userInfor.userId
					post('/problem/insert', this.FormData)
					      .then(data => {
							  if(data.code == 200) {
								  uni.showToast({
								  	title: '数据保存成功！',
								  	duration: 1000
								  });
								uni.switchTab({
					                url: '/pages/work/index'
					            });
							  } else {
								  uni.showToast({
								    icon: 'none',
								    title: data.message
								  });
							  }
					      })
					      .catch(err => {
					        uni.showToast({
					          icon: 'none',
					          title: '保存失败，请检查接口返回'
					        });
					      });
					
				}).catch(err => {
					console.log('err', err);
				})
				/* this.FormData.checkUserId = this.userInfor.userId
						this.FormData.workshopId = this.userInfor.workshopId
						console.log(this.FormData, 'this.FormData')
						post('/problem/insert', this.FormData)
						      .then(data => {
								  if(data.code == 200) {
									  uni.showToast({
									  	title: '数据保存成功！',
									  	duration: 1000
									  });
									uni.switchTab({
						                url: '/pages/position/posAll/index'
						            });
									this.FormData.frontImage = ''
								  } else {
									  uni.showToast({
									    icon: 'none',
									    title: data.message
									  });
								  }
						      })
						      .catch(err => {
						        uni.showToast({
						          icon: 'none',
						          title: '保存失败，请检查接口返回'
						        });
						      }); */
				/* if(!this.FormData.frontImage) {
					uni.showToast({
						icon: 'none',
						title: '请检查上传图片！'
					});
					return;
				} else {
					if(!this.FormData.name || !this.FormData.description || !this.FormData.workshopareaId) {
						uni.showToast({
							icon: 'none',
							title: '请检查问题、区域、问题描述是否为空！'
						});
						return;
					} else {
						
					}
				} */
				
			},
			//获取用户车间、区域信息
			updataInfor() {
				let shop = this.userInfor.workshopList
				let shopData = []
				for(var i = 0; i < shop.length; i++) {
					shopData[i] = {}
					shopData[i].value = shop[i].id
					shopData[i].text = shop[i].workshopName
				}
				this.shopOption = shopData
				if(this.shopOption.length > 1) {
					this.singleShop = false
				} else {
					this.singleShop = true
					this.FormData.workshopId = shopData[0].text
					this.getInfor(shop[0].id)
				}
				
			},
			//车间、检车区域查询
			getInfor(id) {
				//区域
				postForm('/workshop-area-base/findById', {workShopId: id} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							this.spaceOption = []
							this.FormData.workshopareaId = ''
							if(data.data.areas) {
							let area = data.data.areas
							let areaData = []
							for(var i = 0; i < area.length; i++) {
								areaData[i] = {}
								areaData[i].value = area[i].id
								areaData[i].text = area[i].areaName
							}
							this.spaceOption = areaData
							}
							//console.log(this.FormData)
							//debugger
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			progress() {
				console.log('sssss')
				//debugger
			},
			//文件上传
			async onFileChange(event) {
				//console.log(event,'event')
				if(this.FormData.frontImage == '') {
					try {
					  const files = event.tempFiles; // 获取选择的文件列表
					  
					  if (!files || files.length === 0) {
					    uni.showToast({
					      title: '请选择文件',
					      icon: 'none',
					      duration: 2000
					    });
					    return;
					  }
						const filePath = files[0].path; // 获取文件路径
					    
					    // 显示加载提示
					    uni.showLoading({
					      title: '上传中...',
					      mask: true
					    });
					//console.log(filePath)
					//debugger
					    // 使用 fileUpLoad 上传文件
					    let response = await fileUpLoad('/alone/uploadImages', filePath);
					    
					    // 隐藏加载提示
					    uni.hideLoading();
						let fileUrl = ''
					    // response 现在可能是文件URL字符串或后端返回的 data 对象
					    fileUrl = response;
					    if (fileUrl) {
					      // 存储上传文件的URL
						  this.FormData.frontImage = fileUrl
					      //this.uploadedFiles.push(fileUrl);
					      
					      uni.showToast({
					        title: '上传成功，等待提交！',
					        icon: 'success',
					        duration: 2000
					      });
					    }
					} catch (error) {
					  uni.hideLoading();
					  uni.showToast({
					    title: '上传失败，请重试',
					    icon: 'none',
					    duration: 2000
					  });
					  console.error('文件上传错误:', error);
					}
				} else {
					uni.showToast({
					  title: '只允许上传一张图片',
					  icon: 'none',
					  duration: 2000
					});
					return false;
				}
				//debugger
				
			},
			//图片删除
			imgDelet(e) {
				console.log(e)
				e = ''
				this.FormData.frontImage = ''
			},
			shopChange(e) {
				postForm('/workshop-area-base/findById', {workShopId: e} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							this.spaceOption = []
							this.FormData.workshopareaId = ''
							if(data.data.areas) {
							let area = data.data.areas
							let areaData = []
							for(var i = 0; i < area.length; i++) {
								areaData[i] = {}
								areaData[i].value = area[i].id
								areaData[i].text = area[i].areaName
							}
							this.spaceOption = areaData
							}
							//console.log(this.FormData)
							//debugger
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
		    change(e) {
				this.FormData.createTime = e
				console.log('change事件:', this.single = e);
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			maskClick(e){
				console.log('maskClick事件:', e);
			}
		}
	}
</script>

<style>
	/* 模糊搜索弹框样式 */
	.recommendations-box {
	  background-color: #fff;
	box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
	  padding: 10px;
	  width: 80% !important;
	  max-height: 300px;
	  overflow-y: auto;
	  border-radius: 10px;
	}
	
	.recommendation-item {
		font-size: 15px;
	  /* padding: 10px;
	  border-bottom: 1px solid #eee; */
	}
	
	.recommendation-item:last-child {
	  border-bottom: none;
	}
	.uni-button-color {
		margin-top: 50px;
		background-color: #007aff !important;
	}
	/* .uni-forms-item {
	    margin-bottom: 16px !important;
	} */
	.is-disabled {
	    color: #000 !important;
	}
	/* uni-form  lable样式 */
	.uni-forms-item__label {
		font-weight: 600 !important;
		width: 80px !important;
	  text-align: right !important;
	  justify-content: flex-end !important;
	}
	.uni-stat__select {
	    display: flex;
	    align-items: center;
	    width: 100%;
	    flex: 1;
		height: 35px;
	    box-sizing: border-box;
		border: 1px solid #e5e5e5;
	}
	.uni-data-checklist {
	    display: flex;
	    flex: 1;
	    align-items: center !important;
	}
	
</style>
